/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<template>
    <div class="history-version__container">
        <div v-if="showPreviewFlag"
             class="table-data">
            <sf-grid>
                <sf-table
                    ref="table"
                    :options="options_fix"
                    @pagechange="_onPageChange"
                    @sizechange="_onSizeChange">
                    <sf-table-column :default-width="30"
                                     type="index">
                        <lang>序号</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="version"
                        :default-width="60">
                        <lang>版本</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="updateTime"
                        :default-width="100">
                        <lang>提交日期</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="algorithmName"
                        :default-width="60">
                        <lang>算法模板</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="dataSourceName"
                        :default-width="60">
                        <lang>数据集</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="hyperParams"
                        :default-width="120">
                        <lang>超参数</lang>
                    </sf-table-column>
                    <sf-table-column
                        data-index="taskName"
                        :default-width="100">
                        <lang>所属任务</lang>
                    </sf-table-column>
                    <sf-table-column data-index="opr"
                                     :default-width="100">
                        <lang>操作</lang>
                    </sf-table-column>
                    <!--额外操作-->
                    <template slot="hyperParams"
                              slot-scope="{value}">
                        <span :title="handleHyperParams(value)"
                              class="sfv-ellipsis">{{ handleHyperParams(value) }}</span>
                    </template>
                    <!--额外操作-->
                    <template slot="createTime"
                              slot-scope="{value}">
                        <span>{{ encodeTime(value) }}</span>
                    </template>
                    <template slot="opr"
                              slot-scope="{record}">
                        <div class="table-opr">
                            <a
                                class="link-btn"
                                @click="_previewVersionDetail(record)">
                                <lang>查看</lang>
                            </a>
                            <a
                                class="link-btn"
                                @click="_clickReturnVersion(record)">
                                <lang>回滚</lang>
                            </a>
                        </div>
                    </template>
                </sf-table>
            </sf-grid>
        </div>
        <div v-else
             class="preview-detail__wrap">
            <div class="return">
                <span class="icon iconfont iconsip-return"
                      :title="_('查看版本列表')"
                      @click="showPreviewFlag = true"></span>
                <span>{{ versionName }}</span>
            </div>
            <sf-button-primary
                size="small"
                class="btns"
                @click="_previewReturnVersion">
                <lang>回滚</lang>
            </sf-button-primary>
            <div class="preview-detail__container">
                <sf-tab-panel ref="optionsTabpanel"
                              class="detail-tab"
                              size="large"
                              :tab-width="48"
                              :title-hide="true">
                    <sf-tab-item :title="_('特征处理')">
                        <preview-feature :rule-graph-list="ruleGraphList" />
                    </sf-tab-item>
                    <sf-tab-item :title="_('模型训练')">
                        <training-detail :training-info="trainingInfo" />
                    </sf-tab-item>
                </sf-tab-panel>
            </div>
        </div>
    </div>
</template>

<script lang="ts">

import { Component, Vue, Prop} from 'vue-property-decorator';
import { encodeDate } from 'src/util/format';
const PAGE_COUNT = 20;
import parseJson from 'src/util/parse_json';
import trainingUrlAdapter from 'src/home/mod_common/training_url_adapter';
const FLOW_URL = {
    get: trainingUrlAdapter('flow'),
    delete: trainingUrlAdapter('flow'),
    post:trainingUrlAdapter('flow'),
    update:trainingUrlAdapter('flow'),
    review:trainingUrlAdapter('flow/-/snapshot')
};

import PreviewFeature from 'src/home/mod_cluster/project_manager/components/common/preview/preview_feature.vue';
import TrainingDetail from 'src/home/mod_cluster/project_manager/components/common/preview/training_detail.vue';


interface SnapshotParams{
    aiFlowSnapshotId: number;
    algorithmName: string;
    dataSourceName: string;
    hyperParams: string;
    taskName: string;
    updateTime: string;
    version: string;
}


@Component({
    components:{
        PreviewFeature,
        TrainingDetail
    }
})
export default class HistoryVersion extends Vue {

    @Prop({
        type:Array,
        default:()=>[]
    }) tableData!: SafeAny[]

    searchParams =  {
        pageSize: PAGE_COUNT,
        pageNum: 0,
        keyword:''
    }
    options_fix = {
        bufferView: false,
        selectionHide: true,

        // 配置这个后才可以实现保持勾选状态
        idProperty: 'id',
        pagination: {
            activePage: 1,
            pageSize: PAGE_COUNT,
            pageSizes: [Number('10'), Number('20'), Number('50')]
        }
    }
    versionName = '';
    trainingInfo = {}
    ruleGraphList = []
    showPreviewFlag = true
    aiFlowSnapshotId = ''

    get aiFlowId () {
        return this.$route.query.aiFlowId || '';
    }

        // 刷新grid
    async refreshGrid () {
        this.showPreviewFlag = true;
        this.$mask();
        // @ts-ignore
        this.searchParams.flowId = this.aiFlowId;
        let jsonData = await this.$ajax.get(`${FLOW_URL.get}/${this.aiFlowId}/snapshots`, this.searchParams);
        this.$unmask();
        let table = this.$refs.table;
        let {success, msg, data} = jsonData;
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            // @ts-ignore
            table.loadData([]);
            return;
        }
        if (!table) {
            return;
        }
        // @ts-ignore
        table.getPagination().setTotal(data.total);
        // @ts-ignore
        table.loadData(data.list || []);
    }

    //获取图规则
    async getAIPreviewFlowSnapShot (params: SnapshotParams) {
        let getSnapShotURL = `${FLOW_URL.review}/${params.aiFlowSnapshotId}`;

        //  let getGraphURL = `${GRAPG_URL.get}/4`;
        this.$mask();
        let jsonData = await this.$ajax.get(getSnapShotURL);
        let {success, msg, data} = jsonData;
        if (!success) {
            this.$showErr(msg || _('加载数据失败'));
            return;
        };
        this.$unmask();
        let { graphInfo, trainingInfo } = data;
        this.ruleGraphList = parseJson(graphInfo.graphRule);
        this.trainingInfo = trainingInfo;

        //查看完之后报错项目id和项目名称
        // @ts-ignore
        this.aiFlowSnapshotId = params.aiFlowSnapshotId;
        this.versionName = params.version;
    }

    _previewVersionDetail (params: SnapshotParams) {
        this.showPreviewFlag = false;
        this.getAIPreviewFlowSnapShot(params);
    }

    //删除数据源
    _previewReturnVersion () {
        this.confirmReturnVersion();
    }
    _clickReturnVersion (record: SnapshotParams) {
        this.versionName = record.version;
        // @ts-ignore
        this.aiFlowSnapshotId = record.aiFlowSnapshotId;
        this.confirmReturnVersion();
    }
    confirmReturnVersion () {
        // @ts-ignore
        this.$confirm({
            title: _('提示'),
            subTitle: _('确定要回滚到{0}版本吗？', this.versionName),
            msg:_('回滚后，当前的操作将会被覆盖并无法恢复。'),
            icon: 'warning',
            autoClose: true,
            callback: actionName => {
                if (actionName === 'submit') {
                    this.ajaxReturnVersion();
                }
            }
        });
    }

    // 执行回滚操作
    async ajaxReturnVersion () {
        this.$mask();
        let rollbackParams = {
            snapshotId:this.aiFlowSnapshotId
        };
        let jsonData = await this.$ajax.post(`training/v1/flow/${this.aiFlowId}/rollback`, rollbackParams);
        this.$unmask();
        let {success, msg, data} = jsonData;
        if (!success) {
            return this.$showErr(msg || _('回滚失败'));
        }
        this.$ok(_('回滚成功'));
        this.showPreviewFlag = false;
        this.$emit('close-drawer', false, data);
    }



    //编辑数据源


    _onRefresh () {
        this.refreshGrid();
    }

    onEnterkey () {
        this.refreshGrid();
    }

    _onPageChange (pageNum: number) {
        Object.assign(this.searchParams, {
            pageNum: pageNum - 1
        });
        this.refreshGrid();
    }
    _onSizeChange (nowPageIndex: number, nowPageSize: number) {
        Object.assign(this.searchParams, {
            pageNum: nowPageIndex - 1,
            pageSize: nowPageSize
        });
        this.refreshGrid();
    }
    handleHyperParams (hyperParams: string) {
        if (!hyperParams) {
            return '-';
        }
        let jsons = parseJson(hyperParams);
            let list = [];
        if (Array.isArray(jsons)) {
            jsons.forEach(item => {
                // @ts-ignore
                list.push(`${item.paramName} = ${item.value}`);
            });
        } else {
            for (const i in jsons) {
               // @ts-ignore
               list.push(`${i} = ${jsons[i]}`);
            }
        }
        return list.join(' , ');
    }


    encodeTime (time: string) {
        return encodeDate(time);
    }
};
</script>

<style lang="less">
    .history-version__container {
        height: 100%;
        margin-top: -7px;
        .table-data{
            height: 100%;
            .sfv-grid{
                border: none;
                height: 100%;
                display: flex;
                flex-direction: column;
                .sfv-table{
                    flex: 1;
                }
            }
        }
        .sfv-tabpanel .sfv-tabpanel_header .sfv-tabpanel_scroll{
                border-bottom: 1px solid #DEE3ED;
        }
        .sfv-tabpanel.sfv-tabpanel--large .sfv-tabpanel_header .sfv-tabpanel_item{
            background: #fff;
            height: 45px;
            line-height: 45px;
        }
        .preview-detail__wrap{
            height: 100%;
            .return{
                display: flex;
                align-items: center;
                margin-bottom: 16px;
                font-size: 18px;
                position: relative;
                cursor: pointer;
                &::after{
                    content: '';
                    background: #E0E0E0;
                    width: 1px;
                    height: 16px;
                    position: absolute;
                    left: 30px;
                    top: 2px;
                }
                .iconsip-return{
                    color: #204ed9;
                    font-size: 18px;
                    margin-right: 24px;
                    margin-top: -1px;
                }
            }

            .btns{
                margin-bottom: 16px;
            }
            .preview-detail__container{
                height: calc(100% - 80px);
                border:1px solid #ddd;
                .detail-tab{
                    height: 100%;
                }
                .sfv-tabpanel_wrap{
                    height: calc(100% - 44px);
                }
                .tabpanel-body-item{
                     height: 100%;
                }
            }
        }
    }
</style>
